var api = require('../config/api.js');

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

// 将秒数转换为时分秒
function formatSeconds(value) {
  var theTime = parseInt(value); // 秒
  var theTime1 = 0; // 分
  var theTime2 = 0; // 小时
  if (theTime > 60) {
    theTime1 = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (theTime1 > 60) {
      theTime2 = parseInt(theTime1 / 60);
      theTime1 = parseInt(theTime1 % 60);
    }
  }
  var result = "" + parseInt(theTime) + "秒";
  if (theTime1 > 0) {
    result = "" + parseInt(theTime1) + "分" + result;
  }
  if (theTime2 > 0) {
    result = "" + parseInt(theTime2) + "小时" + result;
  }
  return result;
}


function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//时间戳
function timeStamp() {
  return Date.now();
}


/**
 * 小程序的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': method == "GET" ? 'application/json' : 'application/x-www-form-urlencoded',
        'mini-token': wx.getStorageSync('mini-token')
      },
      success: res => {
        if (res.statusCode == 200) {
          if (res.data.code == 0) {
            resolve(res.data);
          } else if (res.data.code == 1001) { //未授权登录
            let code = null;
            login().then(res => {
              code = res.code;
            }).then(res => {
              return getUserInfo();
            }).then(userInfo => {
              request(api.login, {
                code: code,
                fullUserInfo: JSON.stringify(userInfo)
              }, 'POST').then(res => {
                wx.setStorageSync('mini-token', res.data.token);
                wx.setStorageSync('userInfo', res.data.userInfo);

                wx.request({
                  url: url,
                  data: data,
                  method: method,
                  header: {
                    'Content-Type': method == "GET" ? 'application/json' : 'application/x-www-form-urlencoded',
                    'mini-token': res.data.token
                  },
                  success: resp => {
                    if (resp.statusCode == 200) {
                      if (resp.data.code == 0 || resp.data.code == 1201) {
                        resolve(resp.data);
                      } else {
                        showErrorModal(resp.data.msg);
                      }
                    }
                  }
                });
              });
            }).catch(error => {
              console.log(error);
            });
          } else {
            reject(res.data);
            wx.hideLoading();
            showErrorModal(res.data.msg);
          }
        }
      },
      fail: function(err) {
        reject(err)
      }
    })
  });
}

function reqNoAuth(url, data = {}, method = "GET") {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': method == "GET" ? 'application/json' : 'application/x-www-form-urlencoded',
        'mini-token': wx.getStorageSync('mini-token')
      },
      success: res => {
        if (res.statusCode == 200) {
          resolve(res.data);
        }
      }
    });
  });
}
/**
 * 调用微信登录
 */
function login() {
  return new Promise(function(resolve, reject) {
    wx.login({
      success: function(res) {
        if (res.code) {
          //登录远程服务器
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function(err) {
        reject(err);
      }
    });
  });
}

function getUserInfo() {
  return new Promise(function(resolve, reject) {
    console.log('getUserInfo');
    wx.getUserInfo({
      withCredentials: true,
      success: function(res) {
        resolve(res);
      },
      fail: function(err) {
        wx.navigateTo({
          url: '/pages/authorization/authorization'
        })
      }
    })
  });
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    icon: 'loading',
  })
}
// 错误提示
function showErrorModal(msg) {
  wx.showModal({
    title: '温馨提示',
    content: msg,
    showCancel: false
  })
}


module.exports = {
  timeStamp,
  formatTime,
  request,
  reqNoAuth,
  showErrorModal,
  showErrorToast,
  getUserInfo,
  formatSeconds,
}